package com.huatai.paas.websocket;

import com.alibaba.fastjson.JSONObject;
import com.huatai.common.util.CommonUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class StatusChangeWebsocketHandler extends TextWebSocketHandler {

	private static final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

	private static final ExecutorService executorService = Executors.newCachedThreadPool();

	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {

		String pathQuery = session.getUri().getQuery();
		Map<String, String> paramMap = CommonUtils.formatUrlParams(pathQuery);
		String ts = paramMap.get("ts");
		String sessionKey = "project-status" + "-" + ts;
		if (sessions.get(sessionKey) == null) {
			sessions.put(sessionKey, session);
		}
	}
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		String pathQuery = session.getUri().getQuery();
		Map<String, String> paramMap = CommonUtils.formatUrlParams(pathQuery);
		String ts = paramMap.get("ts");
		String sessionKey = "project-status" + "-" + ts;
		sessions.remove(sessionKey);
	}

	/**
	 * 根据用户id发送给某一个用户
	**/
    public boolean sendMessageToAllUser(String total , Object message) {
		JSONObject processedMessage = null;
		if (message != null) {
			processedMessage = (JSONObject) JSONObject.toJSON(message);
			Object id = processedMessage.get("id");
			if (id != null && !(id instanceof String)) {
				processedMessage.put("id", id.toString());
			}
		}
		for (String s : sessions.keySet()) {
			WebSocketSession session = sessions.get(s);
			if (session == null){
				continue;
			}
			if (!session.isOpen()) {
				continue;
			}
			try {
				JSONObject json = new JSONObject();
				json.put("total", total);
				json.put("message", processedMessage);
				session.sendMessage(new TextMessage(json.toJSONString()));
			} catch (IOException e) {
				e.printStackTrace();
				System.out.println("用户【"+s+"】推送信息失败");
			}
        }
        return true;
    }
}
